package nl.cmkprojects.sage.slimplayer;

import gkusnick.sagetv.api.API;
import gkusnick.sagetv.api.AiringAPI;
import gkusnick.sagetv.api.CaptureDeviceInputAPI;
import gkusnick.sagetv.api.ChannelAPI;
import gkusnick.sagetv.api.AiringAPI.Airing;
import gkusnick.sagetv.api.CaptureDeviceInputAPI.CaptureDeviceInput;
import gkusnick.sagetv.api.ChannelAPI.Channel;
import gkusnick.sagetv.api.ChannelAPI.List;
import gkusnick.sagetv.api.WidgetAPI.Widget;

import java.lang.reflect.InvocationTargetException;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import sage.SageTV;

public class SageTVApi {
	private static final String SLIMPLAYER_STANDALONE = "slimplayer.standalone";
	private static Logger logger = Logger.getLogger(SageTVApi.class);

	public static String DurFormat(long time) {
		if (Boolean.getBoolean(SLIMPLAYER_STANDALONE) == false) {
			try {
				return (String) SageTV.api("DurFormat", new Object[] {
						"%d:%h:%m:%s", new Long(time) });
			} catch (InvocationTargetException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return "" + time;
	}

	public static void stopSageTvMediaPlayer(String uiContext) {

		if (Boolean.getBoolean(SLIMPLAYER_STANDALONE) == false) {
			try {
				logger.debug("calling CloseAndWaitUntilClosed() for context:"
						+ uiContext);
				if (uiContext != null) {
					SageTV.apiUI(uiContext, "CloseAndWaitUntilClosed", null);
				} else {
					SageTV.api("CloseAndWaitUntilClosed", null);
				}
			} catch (InvocationTargetException e) {
				logger.error("CloseAndWaitUntilClosed", e);
			}
		}
	}

	/**
	 * WatchLive. This is not working with the universal network encoder. Use
	 * {@link #watchShow(String, String)} instead.
	 * 
	 * @param uiContext
	 * @param device
	 * @param buffer
	 */
	public static void watchLive(String uiContext, String device, long buffer) {
		if (Boolean.getBoolean(SLIMPLAYER_STANDALONE) == false) {
			try {
				logger.debug("calling WatchLive() for context:" + uiContext);
				if (uiContext != null) {
					SageTV.apiUI(uiContext, "WatchLive", new Object[] { device,
							new Long(buffer) });
				} else {
					SageTV.api("WatchLive", new Object[] { device,
							new Long(buffer) });

				}
			} catch (InvocationTargetException e) {
				logger.error("WatchLive", e);
			}
		}
	}

	public static void makeMenuTransition(String uiContext,
			String currentMenuName, String nextMenuName) {
		if (Boolean.getBoolean(SLIMPLAYER_STANDALONE) == false) {
			logger.debug("time to transit to Now Playing Menu(" + uiContext
					+ ")");
			API api = uiContext != null ? new API(uiContext) : new API();
			Widget currentMenu = api.widgetAPI.GetCurrentMenuWidget();
			// current widget must be slimplayer main menu
			if (currentMenuName.equals(currentMenu.GetWidgetName())) {
				Widget nextMenu = api.widgetAPI.FindWidget("Menu", nextMenuName);
				nextMenu.LaunchMenuWidget();
			}
		}
	}

	public static void watchShow(String uiContext, String captureDeviceInput, String stationID) {
		if (Boolean.getBoolean(SLIMPLAYER_STANDALONE) == false) {
			logger.debug("calling WatchShow(" + uiContext + ", "
					+ captureDeviceInput + ")");
			API api = uiContext != null ? new API(uiContext) : new API();
			CaptureDeviceInputAPI.List inputList = api.captureDeviceAPI
					.GetConfiguredCaptureDeviceInputs();
			for (CaptureDeviceInput input : inputList) {
				logger.debug("WatchShow input=" + input.toString());

				if (input.toString().equals("Wrapped " + captureDeviceInput)) {
					String lineup = input.GetLineupForCaptureDeviceInput();
					logger.debug("WatchShow lineup = " + lineup);
					if (StringUtils.isNotEmpty(lineup)) {
						ChannelAPI.List channelsOnLineup = api.database.GetChannelsOnLineup(lineup);
						for (Channel chan : channelsOnLineup) {
							if (StringUtils.isEmpty(stationID) || new Integer(chan.GetStationID()).toString().equals(stationID)){
								AiringAPI.List list = api.database
										.GetAiringsOnChannelAtTime(chan, System
												.currentTimeMillis(), System
												.currentTimeMillis() + 60000,
												false);
								Airing airing = list.get(0);
								airing.Watch();
								break;
							}
						}
					}
					break;
				}
			}
		}
	}

	public static void watchSeekToLive(String uiContext) {
		if (Boolean.getBoolean(SLIMPLAYER_STANDALONE) == false) {
			logger.debug("calling Seek() for context:" + uiContext);
			API api = uiContext != null ? new API(uiContext) : new API();
			api.mediaPlayerAPI.Seek(System.currentTimeMillis());
		}
	}

	public static String getCaptureDeviceInputBeingViewed(String uiContext) {
		if (Boolean.getBoolean(SLIMPLAYER_STANDALONE) == false) {
			try {
				logger
						.debug("calling GetCaptureDeviceInputBeingViewed() for context:"
								+ uiContext);
				if (uiContext != null) {
					return (String) SageTV.apiUI(uiContext,
							"GetCaptureDeviceInputBeingViewed", null);
				} else {
					return (String) SageTV.api(
							"GetCaptureDeviceInputBeingViewed", null);
				}
			} catch (InvocationTargetException e) {
				logger.error("GetCaptureDeviceInputBeingViewed", e);
			}
		}
		return "";
	}

	public static void refreshGui(String uiContext) {
		logger.debug("Refreshing Sage GUI");
		if (Boolean.getBoolean(SLIMPLAYER_STANDALONE) == false) {
			try {
				logger.debug("calling Refresh() for context:" + uiContext);
				if (uiContext != null) {

					SageTV.apiUI(uiContext, "Refresh", null);
				} else {
					SageTV.api("Refresh", null);

				}
			} catch (InvocationTargetException e) {
				logger.error("failed to refresh sage gui", e);
			}
		}
	}

	public static void refreshGuiArea(String uiContext, String panel) {
		logger.debug("Refreshing Sage GUI Area");
		if (Boolean.getBoolean(SLIMPLAYER_STANDALONE) == false) {
			try {
				if (uiContext != null) {
					SageTV.apiUI(uiContext, "RefreshArea",
							new String[] { panel });
				} else {
					SageTV.api("RefreshArea", new String[] { panel });
				}
			} catch (InvocationTargetException e) {
				logger.error("failed to refresh sage gui Area", e);
			}
		}
	}

}